package com.envy.kickoffuserjson.filter;

import com.envy.kickoffuserjson.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class EnvyLoginFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if(!request.getMethod().equals("POST")){
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }else{
            //判断请求类型
            if(request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) ||request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)){
                //说明此时使用的JSON方式
                Map<String,String> loginData = new HashMap<>();
                try{
                    loginData = new ObjectMapper().readValue(request.getInputStream(),Map.class);
                }catch (IOException e){
                    e.printStackTrace();
                }
                String username =loginData.get(getUsernameParameter());
                String password =loginData.get(getPasswordParameter());

                username = username != null ?username.trim():"";
                password = password != null ?password:"";

                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password);
                this.setDetails(request,authenticationToken);

                //新增内容
                User user = new User();
                user.setUsername(username);
                sessionRegistry.registerNewSession(request.getSession(true).getId(),user);

                return this.getAuthenticationManager().authenticate(authenticationToken);
            }else {
                //说明此时使用的是Key/Value键值对方式
                return super.attemptAuthentication(request,response);
            }
        }
    }
}
